package com.sykuku.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sykuku.controller.expection.BusinessException;
import com.sykuku.dao.SetmealDishMapper;
import com.sykuku.dao.SetmealMapper;
import com.sykuku.dto.SetmealDto;
import com.sykuku.pojo.Setmeal;
import com.sykuku.pojo.SetmealDish;
import com.sykuku.service.SetmealDishService;
import com.sykuku.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Transactional//新增套餐
    @Override
    public void setmealWithDish(SetmealDto setmealDto) {
        //添加至setmeal表中
        save(setmealDto);
        //获得套菜中的菜品信息 设置外键关联 保存到中间表中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDishMapper.insert(setmealDish);
            return setmealDish;
        });


    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //根据id和状态查询出对象
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);

        int count = count(queryWrapper);

        if (count>0){
            throw new BusinessException(1,"改套餐正在售卖中,不能删除");
        }
        //删除setmeal表中的数据
        removeByIds(ids);

        //删除中间表中的数据
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishMapper.deleteById(lambdaQueryWrapper);

    }
}
